package com.opoc.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

public class JavaBeanUtils {

  /**
   * 对象转Map
   */
  public static Map<String, Object> beanToMap(Object object) throws IllegalAccessException {
    Map<String, Object> map = new HashMap<>();
    Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
      field.setAccessible(true);
      map.put(field.getName(), field.get(object));
    }
    return map;
  }

  /**
   * map转对象
   */
  public static <T> T mapToBean(Map map, Class<T> beanClass) throws Exception {
    //通过传递进来的JavaBean类新建一个对象
    T object = beanClass.getDeclaredConstructor().newInstance();
    //获取该对象申明的所有字段值
    Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
      //获取修饰符
      int mod = field.getModifiers();
      //静态和final字段跳过
      if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
        continue;
      }
      //字段设置为可访问
      field.setAccessible(true);
      //如果字段key匹配，放入值
      if (map.containsKey(field.getName())) {
        field.set(object, map.get(field.getName()));
      }
    }
    return object;
  }

}
